<template>
<div>
  <el-upload
      class="avatar-uploader"
      :action="url"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="uploadSectionFile"
      :limit="9"
      v-bind="$attrs"
      v-model:file-list="fileList"

  >
    <el-button type="primary">点击上传</el-button>
  </el-upload>
</div>
</template>

<script setup>
import {ElMessage} from "element-plus";
import {getToken} from "@/utils/cookie";
import {upload} from "@/api"

const props = defineProps(['modelValue','uploadUrl'])
const emits = defineEmits(['update:modelValue','change'])
//const url = import.meta.env.VITE_APP_BASE_API + props.uploadUrl ? props.uploadUrl : '/upload';


const getCookie = (name) => {
  const cookies = document.cookie.split('; ');
  for (let i = 0; i < cookies.length; i++) {
    const [key, value] = cookies[i].split('=');
    if (key === name) {
      return value;
    }
  }
  return '';
};
var token = getCookie('XSRF-TOKEN');

console.log('token',getCookie('XSRF-TOKEN'));

const url = computed(()=>{
  let VITE_APP_BASE_API = import.meta.env.VITE_APP_BASE_API;
  return  props.uploadUrl ? VITE_APP_BASE_API + props.uploadUrl : VITE_APP_BASE_API + '/upload';
})
const headers = {
  Authorization:'Bearer ' + getToken(),
  'X-XSRF-TOKEN':token
}

watch(()=>props.modelValue,val=>{
  fileList.value = val;
})
const fileList = ref([])
const handleAvatarSuccess = file=>{
  let list = [];
  fileList.value.forEach(i=>{
    if(i?.status === 'success'){
      list.push({
        status:'success',
        url:i.url || i.response.data.url,
        name:i.name || i.response.data.name,
        id:i.id || i.response.data.id
      });
    }
  });
  // fileList.value = list;
  emits('update:modelValue',list);
  emits('change',file);
}
const beforeAvatarUpload = (rawFile) => {
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error('Avatar picture size can not exceed 2MB!')
  //   return false
  // }
  return true
}

const uploadSectionFile = param => {
     
      // FormData 对象
      var formData = new FormData()
      // 文件对象
      formData.append('file', param.file)
      upload(formData).then(res => {
        console.log('res=>>',res,fileList.value);
        //this.$store.commit("updateAvatar", res.data);
        //this.avatar = res.data;
        //this.$toast({ type: "success", message: "上传成功" });
        // fileList.value.push(res)
        let list = [];
        fileList.value = fileList.value.concat({
              status:'success',
              url:res.data.url,
              name:res.data.name,
              id:res.data.id
            });
            fileList.value = fileList.value.filter(i=>i.status === 'success')
        //fileList.value = list;
        emits('update:modelValue',fileList.value);
        emits('change',param.file);
      }).catch(err =>{
        //this.$toast({ type: "error", message: err.message });
        console.log(err);
        ElMessage.error( err.message)
      })
     
    }
</script>

<style scoped>

</style>